<template>
  <view class="question-list">
    <view class="header">
      <text class="title">答题列表</text>
    </view>

    <scroll-view
        class="list-container"
        scroll-y="true"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        :lower-threshold="100"
        enable-back-to-top="true">

      <view v-if="loading && questionList.length === 0" class="loading">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>

      <view v-else-if="questionList.length === 0 && !loading" class="empty">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
        <text>暂无题目</text>
      </view>

      <view v-else class="question-items">
        <view class="question-items-content">
          <view v-for="(item, index) in questionList"
                :key="index"
                class="question-item"
                :class="{'question-item-hover': item.hover, 'question-item-answered': item.hasAnswer}"
                @tap="startAnswer(item)"
                @touchstart="item.hover = true"
                @touchend="item.hover = false">
            <view class="question-info">
              <text class="question-title">{{ item.questionTitle }}</text>
              <view class="question-meta">
                <view class="tag question-type">{{ getQuestionTypeLabel(item.questionType) }}</view>
                <view class="tag points">
                  <text class="iconfont icon-star"></text>
                  <text>{{ item.rewardPoints }}</text>
                </view>
                <!-- 修复：正确显示答题状态 -->
                <view v-if="item.hasAnswer" class="tag" :class="item.lastAnswerCorrect ? 'correct' : 'wrong'">
                  {{ item.lastAnswerCorrect ? '已答对' : '已答错' }}
                </view>
                <view v-else class="tag not-answered">
                  未答题
                </view>
              </view>
            </view>
            <view class="question-stats">
              <view class="stat-item">
                <text class="stat-label">答题次数</text>
                <text class="stat-value">{{ item.answerCount || 0 }}</text>
              </view>
              <view class="stat-item">
                <text class="stat-label">正确率</text>
                <text class="stat-value" :class="{'high-rate': getCorrectRate(item) >= 80}">{{ getCorrectRate(item) }}%</text>
              </view>
            </view>
            <!-- 已答题的遮罩 -->
            <!-- <view v-if="item.hasAnswer" class="answered-overlay">
              <text class="answered-text">{{ item.lastAnswerCorrect ? '已答对' : '已答错' }}</text>
              <text class="view-record-text">点击查看答题记录</text>
            </view> -->
          </view>
        </view>

        <!-- 加载更多状态 -->
        <view v-if="loadingMore" class="load-more-loading">
          <view class="loading-spinner small"></view>
          <text>加载更多...</text>
        </view>

        <!-- 没有更多数据 -->
        <view v-if="noMore && questionList.length > 0" class="no-more">
          <text>已加载全部数据</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { listQuestion } from "@/api/question/question";
import { listRecord } from "@/api/answerRecord/record";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { getDicts } from "@/api/system/dict/data";
import { getUserProfile } from "@/api/system/user";

const loading = ref(true)
const loadingMore = ref(false)
const refreshing = ref(false)
const noMore = ref(false)
const questionList = ref([])
const dict = ref({
  type: {
    question_type: []
  }
})
const userId = ref(null)
const articleId = ref(null)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  questionStatus: '1',
  generatedTextId: null
})

onLoad((options) => {
  const receivedArticleId = options.articleId
  if (receivedArticleId) {
    articleId.value = receivedArticleId
    queryParams.value.generatedTextId = receivedArticleId
    console.log('接收到的文章ID:', receivedArticleId)
  }

  getDicts("question_type").then(response => {
    dict.value.type.question_type = response.data;
  });

  getUserProfile().then(res => {
    userId.value = Number(res.data.userId)
    getList()
  })
})

onShow(() => {
  if (userId.value) {
    resetAndReload()
  }
})

function resetAndReload() {
  queryParams.value.pageNum = 1
  noMore.value = false
  questionList.value = []
  getList()
}

function onRefresh() {
  refreshing.value = true
  resetAndReload()
  setTimeout(() => {
    refreshing.value = false
  }, 1000)
}

function loadMore() {
  if (loadingMore.value || noMore.value || loading.value) {
    return
  }
  queryParams.value.pageNum++
  getList(true)
}

// 修复：获取题目列表并匹配答题记录
async function getList(isLoadMore = false) {
  if (isLoadMore) {
    if (loadingMore.value || noMore.value) return;
    loadingMore.value = true;
  } else {
    loading.value = true;
  }

  try {
    // 获取题目列表
    const response = await listQuestion(queryParams.value);
    const rows = response.rows || response.data || [];
    const total = response.total || 0;

    // 获取用户的答题记录
    const recordResponse = await listRecord({
      pageNum: 1,
      pageSize: 10000,
      userId: userId.value
    });
    const records = recordResponse.rows || recordResponse.data || [];

    // 创建答题记录映射
    const recordMap = {};
    records.forEach(record => {
      const questionId = String(record.questionId);
      if (!recordMap[questionId]) {
        recordMap[questionId] = [];
      }
      recordMap[questionId].push(record);
    });

    // 处理题目数据，添加答题状态
    const newQuestions = rows.map(item => {
      const questionId = String(item.id);
      const questionRecords = recordMap[questionId] || [];

      // 获取最后一次答题记录
      const lastRecord = questionRecords.length > 0
          ? questionRecords.sort((a, b) => new Date(b.answerTime) - new Date(a.answerTime))[0]
          : null;

      // 调试信息
      console.log(`题目 ${item.id} 的原始数据:`, {
        answerCount: item.answerCount,
        correctCount: item.correctCount,
        userRecords: questionRecords.length
      });

      return {
        ...item,
        hover: false,
        hasAnswer: questionRecords.length > 0,
        lastAnswerCorrect: lastRecord ? lastRecord.isCorrect : false,
        // 使用后端返回的总答题次数，而不是用户个人的答题次数
        answerCount: Number(item.answerCount) || 0,
        correctCount: Number(item.correctCount) || 0,
        // 用户个人的答题统计
        userAnswerCount: questionRecords.length,
        userCorrectCount: questionRecords.filter(r => r.isCorrect).length,
        lastRecord
      };
    });

    if (isLoadMore) {
      questionList.value.push(...newQuestions);
    } else {
      questionList.value = newQuestions;
    }

    const hasMoreData = (queryParams.value.pageNum * queryParams.value.pageSize) < total;
    if (!hasMoreData) {
      noMore.value = true;
    }

    if (newQuestions.length === 0 && hasMoreData) {
      queryParams.value.pageNum++;
      await getList(true);
    }
  } catch (err) {
    console.error('获取题目列表失败:', err);
    if (isLoadMore) {
      queryParams.value.pageNum--;
    }
    uni.showToast({
      title: '获取题目列表失败',
      icon: 'none'
    });
  } finally {
    if (isLoadMore) {
      loadingMore.value = false;
    } else {
      loading.value = false;
    }
  }
}

function getCorrectRate(item) {
  // 使用总体正确率，而不是用户个人的正确率
  if (!item.answerCount || item.answerCount === 0) return 0
  return Math.round((item.correctCount / item.answerCount) * 100)
}

function getQuestionTypeLabel(type) {
  const typeDict = dict.value.type.question_type.find(item => item.dictValue === type)
  return typeDict ? typeDict.dictLabel : type
}

// 修复：根据答题状态决定跳转逻辑
function startAnswer(question) {
  if (question.hasAnswer) {
    // 已答题，跳转到答题记录详情，需带上recordId
    // 需要找到该题最后一次答题记录的id
    const lastRecord = question.lastRecord;
    if (lastRecord && lastRecord.id) {
      uni.navigateTo({
        url: `/pages/question/answer?id=${question.id}&recordId=${lastRecord.id}`
      })
    } else {
      // 兜底：无记录id时跳转到答题记录页
      uni.navigateTo({
        url: `/pages/question/record`
      })
    }
  } else {
    // 未答题，正常答题
    const questionIds = questionList.value.map(q => q.id);
    uni.navigateTo({
      url: `/pages/question/answer?id=${question.id}&ids=${JSON.stringify(questionIds)}`
    })
  }
}
</script>

<style>
.question-list {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20px 20px 0;
  text-align: center;
  position: relative;
  flex-shrink: 0;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.list-container {
  flex: 1;
  height: 100%;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-spinner.small {
  width: 20px;
  height: 20px;
  border-width: 2px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty {
  text-align: center;
  padding: 40px;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.empty-image {
  width: 200px;
  height: 200px;
  opacity: 0.5;
}

.question-items {
  padding: 20px;
  padding-top: 10px;
  min-height: 100%;
}

.question-items-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-item {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.question-item::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(24,144,255,0.1), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.question-item-hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.1);
}

.question-item-hover::after {
  opacity: 1;
}

/* 已答题的样式 */
.question-item-answered {
  opacity: 0.8;
}

.question-info {
  margin-bottom: 15px;
}

.question-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  display: block;
  line-height: 1.5;
}

.question-meta {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.question-type {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}

.points {
  background-color: #fff2f0;
  color: #ff4d4f;
  font-weight: 500;
}

.correct {
  background-color: #f6ffed;
  color: #52c41a;
  font-weight: 500;
}

.wrong {
  background-color: #fff2f0;
  color: #ff4d4f;
  font-weight: 500;
}

.not-answered {
  background-color: #f0f0f0;
  color: #999;
  font-weight: 500;
}

.icon-star {
  font-size: 14px;
}

.question-stats {
  display: flex;
  justify-content: space-between;
  padding-top: 15px;
  margin-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #666;
}

.high-rate {
  color: #52c41a;
}

/* 已答题遮罩 */
.answered-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border-radius: 16px;
}

.answered-text {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.view-record-text {
  font-size: 14px;
  color: #666;
}

/* 加载更多状态 */
.load-more-loading {
  text-align: center;
  padding: 20px;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  font-size: 14px;
}

.no-more {
  text-align: center;
  padding: 20px;
  color: #ccc;
  font-size: 14px;
}
</style>
